package cn.yunhe.servlet;


import cn.yunhe.entity.User;
import cn.yunhe.service.UserService;
import cn.yunhe.util.MD5;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/RegServlet")
public class RegServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String userName = request.getParameter("userName");
            String pwd =  request.getParameter("passWord");
            String md5 = MD5.encryptPassword(pwd,userName).toString();
            User user = new User(userName,md5);
            UserService userService = new UserService();
            if(userService.login(user)==null) {
                boolean flag = userService.register(user);

                if (flag) {//注册成功
                    User u = userService.login(user);
                    request.getSession().setAttribute("Curr_User", u);
                    response.sendRedirect("reg-result.jsp");
                } else {//注册失败
                    request.setAttribute("zhuceshibai", "注册失败,请检查填写内容");
                    request.getRequestDispatcher("register.jsp").forward(request, response);
                }
            }else{
                request.setAttribute( "yizhuce","用户已注册,请直接登录");
                request.getRequestDispatcher("login.jsp").forward(request, response);
            }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
